//
//  MSBannerView.m
//  PeopleForTheFirstMall
//
//  Created by ms on 2022/5/7.
//  Copyright © 2022 MS. All rights reserved.
//

#import "MSBannerView.h"
#import "MSPageControl.h"

@interface MSBannerView ()
<
UICollectionViewDelegate,
UICollectionViewDataSource
>

@property (nonatomic, strong) UICollectionViewFlowLayout *flowLayout;
@property (nonatomic, strong) UICollectionView      *bannerCollectionView;
@property (nonatomic, strong) MSPageControl         *pageControl;
@property (nonatomic, strong) NSTimer               *timer;
@property (nonatomic, strong) UILabel               *pageLabel;
/** banner数量 */
@property (nonatomic, assign) NSInteger             num;

@end

@implementation MSBannerView

- (void)setShowPageLabel:(BOOL)showPageLabel
{
    _showPageLabel = showPageLabel;
    self.pageLabel.hidden = !_showPageLabel;
}
- (void)setShowPageControl:(BOOL)showPageControl
{
    _showPageControl = showPageControl;
    self.pageControl.hidden = !_showPageControl;
}


/** 刷新bannerView */
- (void)reloadBannerView
{
    [self addSubview:self.bannerCollectionView];
    
    [self.bannerCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.equalTo(self);
    }];
    
    [self addSubview:self.pageControl];
    
    [self.pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerX.equalTo(self);
        make.bottom.mas_equalTo(-10 * MS_ADAPTATION_RATIO);
        make.height.mas_equalTo(12 * MS_ADAPTATION_RATIO);
    }];
    
    [self addSubview:self.pageLabel];
    
    [self.pageLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.mas_equalTo(-30 * MS_ADAPTATION_RATIO);
        make.bottom.mas_equalTo(-10 * MS_ADAPTATION_RATIO);
        make.width.mas_equalTo(88 * MS_ADAPTATION_RATIO);
        make.height.mas_equalTo(44 * MS_ADAPTATION_RATIO);
    }];
    
    self.num = self.numberOfItemsInTagsViewBlock ? self.numberOfItemsInTagsViewBlock() : 0;
    self.flowLayout.itemSize = self.sizeForItemInTagsViewBlock ? self.sizeForItemInTagsViewBlock() : CGSizeZero;
    [self.bannerCollectionView reloadData];
    [self setNeedsUpdateConstraints];
    [self updateConstraintsIfNeeded];
    [self setNeedsLayout];
    [self layoutIfNeeded];
    if (self.num > 1)
    {
        [self.bannerCollectionView setContentOffset:CGPointMake(CGRectGetWidth(self.bannerCollectionView.frame), 0)
                                           animated:NO];
    }
    
    self.pageControl.numberOfPages = self.num;
    self.pageControl.currentPage = 0;
    if (self.num > 0)
    {
        self.pageLabel.text = [NSString stringWithFormat:@"1/%ld", self.num];
    }
    
    if (self.animation && self.num > 1)
    {
        [self.timer setFireDate:[NSDate dateWithTimeIntervalSinceNow:3]];
    }
}
- (void)ms_setupSubViews
{
    self.backgroundColor = MS_HEX_COLOR(0xF8F8F8);
    self.scrollEnabled = YES;
}


#pragma mark - timer action

-(void)timerAction
{
    if (self.bannerCollectionView.isScrollEnabled)
    {
        NSInteger index = self.bannerCollectionView.contentOffset.x / CGRectGetWidth(self.bannerCollectionView.frame);
        index++;
        
        NSInteger num = self.num > 1 ? self.num + 2 : self.num;
        if (index == num - 1)
        {
            index = 1;
            [self.bannerCollectionView setContentOffset:CGPointMake(0, 0)
                                               animated:NO];
        }
        
        self.pageControl.currentPage = index - 1;
        self.pageLabel.text = [NSString stringWithFormat:@"%ld/%ld", self.pageControl.currentPage + 1, self.num];
        [self.bannerCollectionView setContentOffset:CGPointMake(CGRectGetWidth(self.bannerCollectionView.frame) * index, 0)
                                           animated:YES];
    }
}


#define mark - UICollectionViewDelegate,UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.num > 1 ? self.num + 2 : self.num;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MSBannerCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MSBannerCollectionViewCell"
                                                                               forIndexPath:indexPath];
    [cell.imgView ms_setImageWithURLString:self.urlForItemBlock ? self.urlForItemBlock([self transformIndex:indexPath.item]) : @""];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.didSelectItemBlock)
    {
        self.didSelectItemBlock([self transformIndex:indexPath.item]);
    }
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (self.scrollViewDidScrollBlock)
    {
        self.scrollViewDidScrollBlock(scrollView);
    }
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if (self.animation && self.num > 1)
    {
        [self.timer setFireDate:[NSDate distantFuture]];
    }
    
    if (self.scrollViewDidScrollBlock)
    {
        self.scrollViewDidScrollBlock(scrollView);
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView == self.bannerCollectionView)
    {
        NSInteger num = self.num > 1 ? self.num + 2 : self.num;
        NSInteger index = scrollView.contentOffset.x / (int)CGRectGetWidth(scrollView.frame);
        
        if (index == 0)
        {
            [self.bannerCollectionView setContentOffset:CGPointMake(CGRectGetWidth(scrollView.frame) * (num - 2), 0)
                                               animated:NO];
            self.pageControl.currentPage = self.num - 1;
            self.pageLabel.text = [NSString stringWithFormat:@"%ld/%ld", self.pageControl.currentPage + 1, self.num];
        }
        else if (index == num - 1)
        {
            [self.bannerCollectionView setContentOffset:CGPointMake(CGRectGetWidth(scrollView.frame), 0)
                                               animated:NO];
            self.pageControl.currentPage = 0;
            self.pageLabel.text = [NSString stringWithFormat:@"%ld/%ld", self.pageControl.currentPage + 1, self.num];
        }
        else
        {
            self.pageControl.currentPage = index - 1;
            self.pageLabel.text = [NSString stringWithFormat:@"%ld/%ld", self.pageControl.currentPage + 1, self.num];
        }
        
        if (self.animation && self.num > 1)
        {
            [self.timer setFireDate:[NSDate dateWithTimeIntervalSinceNow:3]];
        }
    }
    
    if (self.scrollViewDidScrollBlock)
    {
        self.scrollViewDidScrollBlock(scrollView);
    }
}

/** 转换下标，将下标转换为真实数据下标 */
- (NSInteger)transformIndex:(NSInteger)index
{
    if (self.num > 1)
    {
        if (index == 0)
        {
            return self.num - 1;
        }
        else if (index == self.num + 1)
        {
            return 0;
        }
        else
        {
            return index - 1;
        }
    }
    
    return index;
}


#pragma mark - lazy loading

- (UICollectionView *)bannerCollectionView
{
    if (!_bannerCollectionView)
    {
        _bannerCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero
                                                   collectionViewLayout:self.flowLayout];
        _bannerCollectionView.backgroundColor = MS_HEX_COLOR(0xF8F8F8);
        _bannerCollectionView.delegate = self;
        _bannerCollectionView.dataSource = self;
        _bannerCollectionView.bounces = NO;
        _bannerCollectionView.pagingEnabled = YES;
        _bannerCollectionView.showsHorizontalScrollIndicator = NO;
        _bannerCollectionView.showsVerticalScrollIndicator = NO;
        [_bannerCollectionView registerClass:MSBannerCollectionViewCell.class
                  forCellWithReuseIdentifier:@"MSBannerCollectionViewCell"];
    }
    
    return _bannerCollectionView;
}
- (UICollectionViewFlowLayout *)flowLayout
{
    if (!_flowLayout)
    {
        _flowLayout = [[UICollectionViewFlowLayout alloc] init];
        _flowLayout.itemSize = self.sizeForItemInTagsViewBlock ? self.sizeForItemInTagsViewBlock() : CGSizeZero;
        _flowLayout.minimumLineSpacing = 0;
        _flowLayout.minimumInteritemSpacing = 0;
        _flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    }
    
    return _flowLayout;
}
- (UILabel *)pageLabel
{
    if (!_pageLabel)
    {
        _pageLabel = [[UILabel alloc] init];
        _pageLabel.backgroundColor = MS_HEX_COLOR_AND_ALPHA(0x000000, 0.4);
        _pageLabel.font = MS_BOLD_SYSTEM_FONT_OF_SIZE(12);
        _pageLabel.textColor = UIColor.whiteColor;
        _pageLabel.textAlignment = NSTextAlignmentCenter;
        _pageLabel.hidden = YES;
        [_pageLabel ms_makeChains:^(MSChainMaker * _Nonnull make) {
            make.ms_cornerRadii(24 * MS_ADAPTATION_RATIO);
        }];
    }
    
    return _pageLabel;
}
- (MSPageControl *)pageControl
{
    if (!_pageControl)
    {
        _pageControl = [[MSPageControl alloc] init];
        _pageControl.activeImage = [UIImage imageNamed:@"currentPageImage"];
        _pageControl.inactiveImage = [UIImage imageNamed:@"pageImage"];
        _pageControl.hidden = YES;
    }
    
    return _pageControl;
}

- (NSTimer *)timer
{
    if (!_timer)
    {
        _timer = [NSTimer scheduledTimerWithTimeInterval:3.0
                                                  target:self
                                                selector:@selector(timerAction)
                                                userInfo:nil
                                                 repeats:YES];
    }
    
    return _timer;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end


@implementation MSBannerCollectionViewCell

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self addSubview:self.imgView];
        
        [self.imgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self);
        }];
    }
    return self;
}

- (UIImageView *)imgView
{
    if (!_imgView)
    {
        _imgView = [[UIImageView alloc] init];
        _imgView.backgroundColor = MS_HEX_COLOR(0xF8F8F8);
    }
    
    return _imgView;
}

@end
